<script setup>
import { reactive, ref,onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
// import { userloginStore, tokenStore } from '../store/store.js';
// // 引入axios编写api
// 修改：原只引入用户登录API，现补充引入管理员登录API（需确保路径正确）
import userLoginApi from '../api/login_api.js' // 用户登录API
import adminLoginApi from '../api/login2_api.js' // 新增：管理员登录API（对应Login2Controller）

// 新增：引入Element Plus单选框组件，用于身份选择
import { ElRadioGroup, ElRadio, ElFormItem } from 'element-plus'
// 新增：引入图标组件（确保与输入框图标匹配）
import { User, Lock, Key } from '@element-plus/icons-vue'

const userlogin = ref({
  user_name: '',
  user_password: '',
  captcha: '',
  key: '',
  // 新增：添加身份标识字段，默认值为'user'（用户登录），'admin'代表管理员登录
  identity: 'user'
});
onMounted(function(){
  localStorage.removeItem("token");//清空token
  loadCaptcha();// 加载验证码
})

// 获取路由对象
const router = useRouter();

// 验证码图片数据
const captcha = ref("");


const onSubmit = async () => {
  try {
    let res;
    // 新增：根据选择的身份，调用对应的登录API
    if (userlogin.value.identity === 'user') {
      // 用户登录：调用原用户登录接口（/login/dologin）
      res = await userLoginApi.login(userlogin.value);
    } else {
      // 管理员登录：调用管理员登录接口（/login2/dologin），需转换参数格式匹配后端
      res = await adminLoginApi.login({
        ad_name: userlogin.value.user_name, // 前端统一用user_name输入，后端管理员需ad_name
        ad_password: userlogin.value.user_password, // 同理，转换为ad_password
        captcha: userlogin.value.captcha,
        key: userlogin.value.key
      });
    }

    if (res) {
      localStorage.setItem("token", res); // 保存返回的token
      // 修改：根据身份跳转不同页面，用户→userindex，管理员→index
      if (userlogin.value.identity === 'user') {
        router.push("/userindex");
      } else {
        router.push("/index");
      }
    }
  } catch (error) {
    // 新增：捕获接口异常，提示错误信息（如用户不存在、密码错误）
    ElMessage.error(error.message || "登录失败，请重试");
  }
}

// 加载验证码
// 新增：验证码加载逻辑（复用原逻辑，无需修改，适配两种登录身份）
const loadCaptcha = async () => {
  // 修改：根据身份加载对应接口的验证码（用户→/login/captcha，管理员→/login2/captcha）
  let captchaRes;
  if (userlogin.value.identity === 'user') {
    captchaRes = await userLoginApi.captcha();
  } else {
    captchaRes = await adminLoginApi.captcha();
  }
  userlogin.value.key = captchaRes.key;
  captcha.value = captchaRes.base; // 验证码图片base64地址
}

// 新增：忘记密码相关变量
const showResetDialog = ref(false);
const resetForm = reactive({
  user_name: '',
  captcha: ''
});
resetForm.captcha1 = undefined;
const sendSuccess = ref(false);
const countDown = ref(60);
let countDownTimer = null;

// 发送验证码
const sendCaptcha = async () => {
  if (!resetForm.user_name) {
    ElMessage.warning('请先输入用户账号');
    return;
  }

  try {
    await userLoginApi.sendResetCaptcha(resetForm.user_name);
    ElMessage.success('验证码已发送到邮箱');
    sendSuccess.value = true;

    // 倒计时逻辑
    countDownTimer = setInterval(() => {
      countDown.value--;
      if (countDown.value <= 0) {
        clearInterval(countDownTimer);
        sendSuccess.value = false;
        countDown.value = 60;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error(error.message || '发送失败');
  }
};

// 确认重置密码
const confirmReset = async () => {
  try {
    await userLoginApi.confirmReset({
      user_name: resetForm.user_name,
      user_password: resetForm.captcha1
    });
    ElMessage.success('密码已重置为123456，请登录');
    showResetDialog.value = false;
    // 清除倒计时
    if (countDownTimer) {
      clearInterval(countDownTimer);
      sendSuccess.value = false;
      countDown.value = 60;
    }
  } catch (error) {
    ElMessage.error(error.message || '重置失败');
  }
};
// 新增：注册相关变量
const showRegisterDialog = ref(false);
const registerForm = reactive({
  user_name: '',
  user_password: '',
  confirm_password: '',
  email: '',
  captcha: '',
  resident_id: '' // 居民ID字段，参考userlogin.vue
});
const registerCaptchaSend = ref(false);
const registerCountDown = ref(60);
let registerTimer = null;

// 新增：发送注册验证码
const sendRegisterCaptcha = async () => {
  if (!registerForm.email) {
    ElMessage.warning('请输入邮箱');
    return;
  }
  if (!registerForm.user_name) {
    ElMessage.warning('请先输入用户名');
    return;
  }

  try {
    // 调用后端发送注册验证码接口（需后端配合实现）
    await userLoginApi.sendRegisterCaptcha(registerForm.user_name, registerForm.email);
    ElMessage.success('注册验证码已发送到邮箱');
    registerCaptchaSend.value = true;

    // 倒计时逻辑
    registerTimer = setInterval(() => {
      registerCountDown.value--;
      if (registerCountDown.value <= 0) {
        clearInterval(registerTimer);
        registerCaptchaSend.value = false;
        registerCountDown.value = 60;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error(error.message || '发送失败');
  }
};
const checkUsernameExists = async () => {
  if (registerForm.user_name) {
    try {
      await userLoginApi.checkUsername(registerForm.user_name);
    } catch (error) {
      ElMessage.warning(error.message || '用户名已存在');
    }
  }
};
// 新增：确认注册
const confirmRegister = async () => {
  // 前端表单验证
  if (registerForm.user_password !== registerForm.confirm_password) {
    ElMessage.error('两次密码输入不一致');
    return;
  }
  if (!registerForm.captcha) {
    ElMessage.error('请输入验证码');
    return;
  }

  try {
    await userLoginApi.register({
      user_name: registerForm.user_name,
      user_password: registerForm.user_password,
      email: registerForm.email,
      captcha: registerForm.captcha,
      resident_id: registerForm.resident_id
    });

    ElMessage.success('注册成功，请登录');
    showRegisterDialog.value = false;

    // 优化：强制清空表单（避免残留数据）
    registerForm.user_name = '';
    registerForm.user_password = '';
    registerForm.confirm_password = '';
    registerForm.email = '';
    registerForm.captcha = '';
    registerForm.resident_id = '';

    // 清除倒计时
    if (registerTimer) {
      clearInterval(registerTimer);
      registerCaptchaSend.value = false;
      registerCountDown.value = 60;
    }
  } catch (error) {
    ElMessage.error(error.message || '注册失败');
  }
};
</script>


<template>
  <div class="login-bg">
    <el-form class="form-login" :model="userlogin">
      <el-row>
        <el-col :span="10">
          <img style="width: 100px" src="@/assets/logo.png" alt="利民宝" />
        </el-col>
        <el-col :span="14">
          <h1>系统登录</h1>
        </el-col>
      </el-row>
      <!-- 新增：登录身份选择单选框组 -->
      <el-form-item label="登录身份" required>
        <el-radio-group v-model="userlogin.identity" @change="loadCaptcha">
          <el-radio label="user">用户登录</el-radio>
          <el-radio label="admin">管理员登录</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 修改：输入框标签文本适配两种身份（原"请输入账号"，现动态显示） -->
      <el-form-item
          label="账号"
          :rules="[{ required: true, message: '请输入' + (userlogin.identity === 'user' ? '用户账号' : '管理员账号'), trigger: 'blur' }]">
        <el-input
            v-model="userlogin.user_name"
            placeholder="请输入"
            :prefix-icon="User"
            maxlength="16"
            clearable>
        </el-input>
      </el-form-item>

      <el-form-item
          label="密码"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
        <el-input
            v-model="userlogin.user_password"
            placeholder="请输入密码"
            show-password
            :prefix-icon="Lock"
            maxlength="16"
            clearable>
        </el-input>
      </el-form-item>

      <!-- 新增：验证码表单校验，确保用户输入 -->
      <el-form-item
          label="验证码"
          :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]">
        <el-input
            v-model="userlogin.captcha"
            placeholder="请输入验证码"
            :prefix-icon="Key"
            maxlength="5"
            class="input-verCode">
        </el-input>
        <!-- 修改：验证码图片点击刷新逻辑保留，适配两种身份 -->
        <img :src="captcha" class="img-verCode" @click="loadCaptcha" alt="验证码">
      </el-form-item>
      <!-- 登录按钮 -->
      <el-form-item>
        <el-button class="btn-login" type="primary" @click="onSubmit">登录</el-button>
      </el-form-item>

      <!-- 忘记密码按钮（仅用户登录显示） -->
      <el-form-item v-if="userlogin.identity === 'user'">
        <el-button type="text" @click="showResetDialog = true">忘记密码</el-button>
      </el-form-item>
      <!-- 新增：注册按钮 -->
      <el-form-item v-if="userlogin.identity === 'user'">
        <el-button type="text" @click="showRegisterDialog = true">新用户注册</el-button>
      </el-form-item>
    </el-form>

    <!-- 忘记密码弹窗 -->
    <el-dialog v-model="showResetDialog" title="重置密码" width="30%">
      <el-form :model="resetForm" >
        <el-form-item label="用户账号" :rules="[{ required: true, message: '请输入用户账号', trigger: 'blur' }]">
          <el-input v-model="resetForm.user_name" placeholder="请输入用户账号"></el-input>
        </el-form-item>

        <el-form-item label="验证码" :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]">
          <el-input v-model="resetForm.captcha1" placeholder="请输入验证码" class="input-verCode"></el-input>
          <el-button @click="sendCaptcha" type="primary" v-if="!sendSuccess">发送验证码</el-button>
          <span v-else>{{ countDown }}秒后重新发送</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showResetDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmReset">确认重置</el-button>
      </template>
    </el-dialog>
    <!-- 新增：注册弹窗 -->
    <el-dialog v-model="showRegisterDialog" title="用户注册" width="35%">
      <el-form :model="registerForm" label-width="100px">
        <el-form-item label="用户名" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="registerForm.user_name" placeholder="请输入用户名" :prefix-icon="User">
            @blur="checkUsernameExists"  <!-- 添加失焦事件 -->
          </el-input>
        </el-form-item>
        <el-form-item label="密码" :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input v-model="registerForm.user_password" type="password" placeholder="请输入密码" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :rules="[{ required: true, message: '请确认密码', trigger: 'blur' }]">
          <el-input v-model="registerForm.confirm_password" type="password" placeholder="请确认密码" :prefix-icon="Lock"></el-input>
        </el-form-item>
        <el-form-item label="居民ID" :rules="[{ required: true, message: '请输入居民ID', trigger: 'blur' }]">
          <el-input v-model="registerForm.resident_id" placeholder="请输入居民ID"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :rules="[{ required: true, message: '请输入邮箱', trigger: 'blur' }, { type: 'email', message: '请输入正确的邮箱格式' }]">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" :prefix-icon="Mail"></el-input>
        </el-form-item>
        <el-form-item label="验证码" :rules="[{ required: true, message: '请输入验证码', trigger: 'blur' }]">
          <el-input v-model="registerForm.captcha" placeholder="请输入验证码" class="input-verCode"></el-input>
          <el-button @click="sendRegisterCaptcha" type="primary" v-if="!registerCaptchaSend">发送验证码</el-button>
          <span v-else>{{ registerCountDown }}秒后重新发送</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRegisterDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmRegister">确认注册</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 修改：原表单宽度280px，新增身份选择后加宽至380px，避免布局拥挤 */
.login-bg {
  height: 100vh;
  background-image: url('@/assets/beijing.png'); /* 修复原路径写法（src前加@） */
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-login {
  width: 380px; /* 原280px，修改为380px适配身份选择框 */
  padding: 30px;
  background-color: #FFF;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 8px; /* 新增：添加圆角，优化视觉 */
}

.btn-login {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

h1 {
  text-align: center;
  font-size: 24px;
  margin: 0;
  color: #333;
}

/* 修改：验证码输入框与图片布局优化，避免重叠 */
.input-verCode {
  width: 65%;
  display: inline-block;
  margin-right: 5%;
}

.img-verCode {
  width: 30%;
  height: 40px;
  vertical-align: middle;
  cursor: pointer;
  border-radius: 4px;
}

/* 新增：调整表单项间距 */
.el-form-item {
  margin-bottom: 15px;
}
</style>